package com.sdy.mvc.feign;

import com.sdy.mvc.utils.JsonUtil;
import feign.Request;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Slf4j
public class FeignSpringBodyEncoder implements Encoder {
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private static final HttpHeaders JSON_HEADERS = new HttpHeaders();
    
    static {
        JSON_HEADERS.setContentType(MediaType.APPLICATION_JSON);
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (isFormRequest(bodyType)) {
            for (Map.Entry<String, List<String>> entry : JSON_HEADERS.entrySet()) {
                template.header(entry.getKey(), entry.getValue());
            }
            RemoteBody remoteBody = new RemoteBody();
            remoteBody.setParamMap((Map<Object, Object>) object);
            byte[] data = JsonUtil.serialize(remoteBody);
            template.body(Request.Body.encoded(data, UTF_8));
        }
    }

    private boolean isFormRequest(Type type) {
        return MAP_STRING_WILDCARD.equals(type);
    }
}